package com.example.sprintboot.controller;

import com.example.sprintboot.service.CartService;
import com.example.sprintboot.vo.CartItemVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import com.example.sprintboot.security.UserDetailsImpl;
import java.util.List;

@RestController
@RequestMapping("/api/cart")
public class CartController {
    @Autowired
    private CartService cartService;

    // 获取当前登录用户userId
    private Integer getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetailsImpl) {
            return ((UserDetailsImpl) authentication.getPrincipal()).getUserId();
        }
        return null;
    }

    @GetMapping
    public List<CartItemVO> getCart() {
        Integer userId = getCurrentUserId();
        return cartService.getCartItems(userId);
    }

    @GetMapping("/items")
    public List<CartItemVO> getCartItems() {
        Integer userId = getCurrentUserId();
        return cartService.getCartItems(userId);
    }

    @PostMapping("/add")
    public String addCartItem(@RequestParam Integer productId, @RequestParam Integer quantity) {
        Integer userId = getCurrentUserId();
        cartService.addCartItem(userId, productId, quantity);
        return "success";
    }

    @PostMapping("/update")
    public String updateCartItem(@RequestParam Integer itemId, @RequestParam Integer quantity, @RequestParam Boolean selected) {
        Integer userId = getCurrentUserId();
        cartService.updateCartItem(userId, itemId, quantity, selected);
        return "success";
    }

    @PostMapping("/delete")
    public String deleteCartItem(@RequestParam Integer itemId) {
        Integer userId = getCurrentUserId();
        cartService.deleteCartItem(userId, itemId);
        return "success";
    }

    @PostMapping("/batchDelete")
    public String batchDeleteCartItems(@RequestBody List<Integer> itemIds) {
        Integer userId = getCurrentUserId();
        cartService.batchDeleteCartItems(userId, itemIds);
        return "success";
    }

    @PostMapping("/clear")
    public String clearCart() {
        Integer userId = getCurrentUserId();
        cartService.clearCart(userId);
        return "success";
    }

    @PostMapping("/merge")
    public String mergeCart(@RequestBody List<CartItemVO> items) {
        Integer userId = getCurrentUserId();
        cartService.mergeCart(userId, items);
        return "success";
    }

    @PostMapping("/batchCheckout")
    public void batchCheckout(@RequestBody List<Integer> itemIds) {
        Integer userId = getCurrentUserId();
        cartService.batchCheckout(userId, itemIds);
    }
} 